﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Chinesys.Domain.InputValidations;
using System.Text;

namespace Chinesys.UI.Helpers
{
    public static class TypeHelper
    {
        public static string[] forbiddenSymbols
        {
            get
            {
                return new string[] 
                {
                    "[", 
                    "]",
                    "<",
                    ">",
                    ";",
                    "{",
                    "}",
                    "select",
                    "insert",
                    "update",
                    "delete",
                    "drop",
                    "javascript",
                    "^",
                    "go",
                    "'",
                    "\""                   

                };
            }
        }

        public static T ConvertToType<T>(object field, string fieldName, List<InputValidationError> errors) where T: IConvertible
        {
            object ret = null;

            try
            {
                Type type = typeof(T);
                ret = Convert.ChangeType(field, type);

                if (type.Name == "String")
                {
                    CheckForbiddenSimbols(field as string, fieldName, errors);
                }

            }
            catch (Exception ex)
            {
                errors.Add(
                    new IncorrectType(fieldName, GetTypeName(typeof(T)))
                         );

                return default(T);
            }



            return (T)ret;
        }

        private static void CheckForbiddenSimbols(string input, string fieldName, List<InputValidationError> errors)
        {
            string [] res = (from symbol in forbiddenSymbols
                      where input.ToLower().Contains(symbol)
                          select symbol).ToArray(); ;

            if (res.Any())
            {
                errors.Add(new InvalidSymbolsError(fieldName, res.ToArray()));                 
            }
        }
                
        private static string GetTypeName(Type type)
        {
            string name = string.Empty;

            switch (type.Name)
            {
                case "Int32": name = "Numero Entero"; break;
                case "Int16": name = "Numero Entero"; break;
                case "String": name = "Texto"; break;
                case "Boolean": name = "Booleano"; break;
                case "Decimal": name = "Numero Decimal"; break;
                case "Float": name = "Numero Decimal"; break;
                case "DateTime": name = "Fecha"; break;
                default: name = "Desconocido"; break;
            }

            return name;
        }
    }
}